#include "widget.h"
#include "ui_widget.h"

// ip address: 192.168.1.4

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    db = QSqlDatabase::database("conn");//链接数据库
    service = new serviceManagement;//定义客服管理窗口为子类，便于传递信息
    connect(service,&serviceManagement::sendText,this,&Widget::sendText);//子类传输含消息的信号，接收消息并且发送给client

    mServer = new QTcpServer;
    bool flag = mServer->listen(QHostAddress::Any,6666);//应用程序端口：6666

    if(flag){
        //QMessageBox::information(this, "提示", "监听成功");//准备接受并且处理消息

        connect(mServer,&QTcpServer::newConnection,this,[this](){
            //当有客户端成功连接到服务器时 会触发newConnection信号
            //mSocket = 连接了客户的通信套接字
            mSocket = mServer->nextPendingConnection();

            //当有新信息时会触发信号readyRead
            connect(mSocket,&QTcpSocket::readyRead,this,[this](){

                char str[1024] = {0};
                mSocket->read(str,sizeof str);//接收客户端信息
                QString message = str;
                qDebug() << message;
                if(message.startsWith("#")){
                    int key = message.split("#",QString::SkipEmptyParts).at(0).toInt();
                    QString content = message.split("#",QString::SkipEmptyParts).at(1);
                    qDebug() << key;
                    switch (key) {
                    case -1:signup(content);return;//对应客户端注册
                    case 0:login(content);return;//对应客户端登录
                    case 2:sendDishes();return;//对应客户端点单
                    case 3:getOrder(content);return;//对应客户端下单
                    case 4:sendFinishedOrder(content);return;//对应客户端查看全部订单
                    case 5:updateComment(content);return;//对应客户端发表评论
                    case 6:chatGet(content);return;//对应客户端发起询问
                    case 7:sendComment(content);return;//对应客户端点击菜品查看评论
                    }
                }
            });
        });
    }else{
        QMessageBox::information(this,"提示","监听失败");
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::sendText(QString text){
    mSocket->write(text.toUtf8());//槽函数，与子窗口发送消息的信号链接，发送信息到客户端
}

void Widget::on_dishesManagementBtn_clicked()
{
    dishes = new dishesManagement;
    dishes->show();//跳转菜品管理窗口
}

void Widget::on_serviceManagementBtn_clicked()
{
    service->show();//跳转客服管理窗口
}

void Widget::on_orderManagementBtn_clicked()
{
    orders = new ordersManagement;
    orders->show();//跳转订单管理窗口
}

void Widget::on_tableManagementBtn_clicked()
{
    table = new tableManagement;
    table->show();//跳转桌位管理窗口
    connect(table,&tableManagement::checkoutSend,this,&Widget::sendText);
}


void Widget::on_discountManagementBtn_clicked()
{
    discount = new discountManagement;
    discount->show();//跳转折扣管理窗口
}

void Widget::on_checkoutManagementBtn_clicked()
{
    checkout = new checkoutManagement;
    checkout->show();//跳转结账管理窗口
    connect(checkout,&checkoutManagement::checkoutSend,this,&Widget::sendText);
}

void Widget::on_turnoverManagementBtn_clicked()
{
    turnover = new turnoverManagement;
    turnover->show();//跳转流水管理窗口
}

void Widget::on_commentManagementBtn_clicked()
{
    comment = new commentManagement;
    comment->show();//跳转评论管理窗口
}

void Widget::login(QString message)
{
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    QString rphone = message.split("&",QString::SkipEmptyParts).at(0);
    QString rpassword = message.split("&",QString::SkipEmptyParts).at(1);
    QString sqlSelect = QString("select * from admin;");
    if(!query.exec(sqlSelect)){
        qDebug() << "select data error" << db.lastError();
        return;
    }else {
        while(query.next()){
            QString name = query.value("name").toString();
            QString phone = query.value("phone").toString();
            QString address = query.value("address").toString();
            QString password = query.value("password").toString();
            if(!(phone == rphone && password == rpassword)){
                continue;
            }else{
                mSocket->write(QString("#0#" + name + "&" + phone + "&" + address).toUtf8());
                return;
            }
        }
        mSocket->write(QString("#0#fail").toUtf8());
    }
}

void Widget::signup(QString message)
{
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    QStringList list = message.split("&",QString::SkipEmptyParts);
    QString name = list.at(0);
    QString phone = list.at(1);
    QString address = list.at(2);
    QString password = list.at(3);

    QString sqlSelect = QString ("select phone from admin;");

    if(!query.exec(sqlSelect)){//查找重复账户
        qDebug() << "select data error" << db.lastError();
    }else {
        if(query.next()){
            if(query.value("phone").toString() == phone){
                mSocket->write(QString("#-1#fail").toUtf8());
                return;
            }else{
                mSocket->write(QString("#-1#success").toUtf8());
            }
        }
    }

    QString sqlInsert = QString("insert into admin (name,phone,address,password) "
                                "values('%1','%2','%3','%4');").arg(name)
            .arg(phone).arg(address).arg(password);

    if(!query.exec(sqlInsert)){
        qDebug() << "insert data error" << db.lastError();
    }
}

void Widget::sendDishes()
{
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);
    QString sqlSelect = QString ("select name, prize, discount from menu where number != 0;");

    if(!query.exec(sqlSelect)){//遍历菜单
        qDebug() << "select data error" << db.lastError();
    }else {
        mSocket->write(QString("#1#").toUtf8());
        while(query.next()){
            QString name = query.value("name").toString();
            int prize = query.value("prize").toInt();
            double discount = query.value("discount").toDouble();
            double currenPrize = prize * discount;
            mSocket->write(QString("%" + name + "&" +
                                   QString::number(prize) + "&" +
                                   QString::number(currenPrize)).toUtf8());
        }
    }
}

void Widget::getOrder(QString message)
{
    QMessageBox::information(this,"提示","您有新的订单");

    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    QStringList list = message.split("&",QString::SkipEmptyParts);
    QString date = QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm");
    QString address = list.at(0);
    QString customer = list.at(1);
    QString phone = list.at(2);
    double prize = list.at(3).toDouble();
    QString content = list.at(4);

    QString sqlInsert = QString("insert into orders (date,address,customer,phone,content,prize) "
                                "values('%1','%2','%3','%4','%5',%6);").arg(date)
            .arg(address).arg(customer).arg(phone).arg(content).arg(prize);
    if(!query.exec(sqlInsert)){
        qDebug() << "insert data error" << db.lastError();
    }

    QStringList dishes = content.split(" ",QString::SkipEmptyParts);//将订单中的菜品分别列出
    foreach(QString name,dishes){
        qDebug() << name;
        int number = 0;
        QString sqlSelect = QString ("select number from menu where name = '%1';").arg(name);
        if(!query.exec(sqlSelect)){//遍历menu表单
            qDebug() << "select data error" << db.lastError();
        }else {
            if(query.next()){//读取数据库，获得对应菜品数量
                number = query.value("number").toInt() - 1;
            }
        }
        qDebug() << number << "before update";
        QString sqlUpdate = QString ("update menu set number = %1 where name = '%2';")
                .arg(number).arg(name);
        if(!query.exec(sqlUpdate)){//菜品数量减一
            qDebug() << "update data error" << db.lastError();
        }
    }
}

void Widget::sendFinishedOrder(QString customer)
{
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);
    QString sqlSelect = QString ("select date, prize, content from orders where customer = '%1';")
            .arg(customer);

    if(!query.exec(sqlSelect)){//遍历订单
        qDebug() << "select data error" << db.lastError();
    }else {
        QString message = "#2#";
        while(query.next()){
            message += "%";
            QString date = query.value("date").toString();
            QString prize = query.value("prize").toString();
            QString content = query.value("content").toString();
            message += date;
            message += "&";
            message += prize;
            message += "&";
            message += content;
        }
        mSocket->write(message.toUtf8());
    }
}

void Widget::updateComment(QString message)
{
    QMessageBox::information(this,"提示","您收到了一条新的菜品评论");

    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    QStringList list = message.split("&",QString::SkipEmptyParts);
    QString dishes = list.at(0);
    QString customer = list.at(1);
    QString date = QDate::currentDate().toString("yyyy/MM/dd");
    QString content = list.at(2);
    QString sqlInsert = QString("insert into comment (dishes,customer,date,content) "
                                "values('%1','%2','%3','%4');").arg(dishes)
            .arg(customer).arg(date).arg(content);

    if(!query.exec(sqlInsert)){
        qDebug() << "insert data error" << db.lastError();
    }
}

void Widget::chatGet(QString comment)
{
    QMessageBox::information(this,"提示","您收到用户发来的一条消息");
    service->textChanged(comment);
}

void Widget::sendComment(QString message)
{

}
